package cn.regexp.redis.service.impl;

import cn.regexp.domain.ShopUser;
import cn.regexp.redis.service.IShopUserRedisService;
import cn.regexp.utils.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class ShopUserRedisServiceImpl implements IShopUserRedisService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    // @Override
    // public void saveVerifyCode(String phone, String code) {
    //     // 参数1：key
    //     // 参数2：value
    //     // 参数3：失效时间
    //     // 参数4：时间单位
    //     redisTemplate.opsForValue().set(RedisKeys.REGISTER_VERIFY_CODE.join(phone), code,
    //             RedisKeys.REGISTER_VERIFY_CODE.getTime(), TimeUnit.SECONDS);
    // }

    // @Override
    // public String getVerifyCode(String phone) {
    //     return redisTemplate.opsForValue().get(RedisKeys.REGISTER_VERIFY_CODE.join(phone));
    // }

    @Override
    public void setToken(String token, String shopUser) {
        redisTemplate.opsForValue().set(RedisKeys.USER_INFO_TOKEN.join(token), shopUser,
                RedisKeys.USER_INFO_TOKEN.getTime(), TimeUnit.DAYS);
    }

    @Override
    public ShopUser getUserByToken(String token) {
        if (!StringUtils.hasLength(token)) {
            return null;
        }
        // 拼接 key
        String key = RedisKeys.USER_INFO_TOKEN.join(token);
        // 判断是否存在该key
        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
            // 获取用户信息
            String shopUser = redisTemplate.opsForValue().get(key);
            // 重置时间
            redisTemplate.expire(key, RedisKeys.USER_INFO_TOKEN.getTime(), TimeUnit.DAYS);
            return JSON.parseObject(shopUser, ShopUser.class);
        }
        return null;
    }
}
